var chart;
var prevUserTime = 0;

function setupGraph(testRunId){
	var loading = loadingGraph();
	loading.showLoading();
	
	$.getJSON("/server/query/responsetime/"+testRunId,{min: 0},function(data){
		var min = 0;
		var responseTimeSeries = [];
		var length = data.responses.length;
		if(length){
			for(var i=0; i<length;i++){
				responseTimeSeries.push([data.responses[i].time, data.responses[i].resp]);
			}
			
			min = data.responses[length-1].time + 1;	
		}
		
		var userMin = 0;
		var userCount = 0;
		var userSeries = [];
		length = data.users.length;
		if(length){
			for(var i=0;i<length;i++){
				userSeries.push([data.users[i].time, data.users[i].count])
			}

			userCount = data.userCount;
		}
		
		if(data.userLatestTime > 0){
			userMin = data.userLatestTime + 1;
		}

		loading.destroy();
		chart = createHighcharts(testRunId, min, userMin, userCount, responseTimeSeries, userSeries);
	});
}

function createHighcharts(testRunId, min, userMin, userCount, responseData, userData) {
	var lcolor = '#00aa00';
	var rcolor = '#000066';

	var seriesinfo = [{ // Left y-axis
		name: 'Response time',
		color: lcolor,
		data: responseData
	},
	{
		name: 'Users',
		yAxis: 1,
		color: rcolor,
		data: userData
	}];
	var yAxes = [{ // (0) Left y-axis
		title: {
			text: 'Response Time (ms)',
			/*style: {
				color: lcolor
			}*/
		},
		labels: {
			style: {
				color: lcolor
			}
		}
	},
    // (1) Right y-axis
	{
      title: {
        text: '# users'
      },
      labels: {
    	  style: {
    		  color: rcolor
    	  }
      },
      opposite: true
	},
	// (2) Right y-axis
	{
      title: {
    	text: ' '
      },
      opposite: true
	}];

	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	
	return new Highcharts.Chart({
		chart: {
			renderTo: 'graph',
			zoomType: 'x',
			type: 'line',
			events: {
					load: function() {
						// set up the updating of the chart every 2 second
						pollResponseTime(this, min, userMin, userCount, false);
					}
				}	
		},
		credits: {
          enabled: false
        },
		title: {
			text: 'Results over Time'
		},
		plotOptions: {
          line: {
            marker: {
              enabled: false
            }
		  }
		},
		xAxis: {
			type: 'datetime'
		},
		yAxis: yAxes,
		tooltip: {
			xDateFormat: '%Y/%m/%d %H:%M:%S',
		},
		series: seriesinfo
	});
};

function pollResponseTime(chart, minimum, userMin, userCount, done){
	setTimeout(function() {

		$.getJSON("/server/query/responsetime/"+testRunId,{min: minimum, userMin: userMin, users: userCount},function(data){
			var length = data.responses.length;
			if(length){
				for(var i=0; i<length;i++){
					chart.series[0].addPoint([data.responses[i].time, data.responses[i].resp], false, false);									
				}
				
				minimum = data.responses[length-1].time + 1;
			}

			length = data.users.length;
			if(length){
				for(var i=0; i<length;i++){
					var time = data.users[i].time
					if(time > prevUserTime) {
						chart.series[1].addPoint([time, data.users[i].count], false, false);
						prevUserTime = time;
					}
				}
				chart.redraw();
			}
			
			if(data.userLatestTime > 0){
				userMin = data.userLatestTime + 1;
			}
			
			if(!done){
				pollResponseTime(chart, minimum, userMin, data.userCount, data.done);
			}
		});

	}, 2000);
}

function addSeries(args){
  if(args.rps){
    chart.yAxis[2].setTitle({
      text: '# requests'
    });
    chart.addSeries({
      name: 'Requests/sec',
      yAxis: 2,
      data: args.rps
    });
  }
  
  if(args.avgresp){
    chart.addSeries({
      name: 'Avg. response time',
      data: args.avgresp
    });
  }
}

function loadingGraph(){
	return new Highcharts.Chart({
		chart: {
			renderTo: 'graph'
		},
		title: {
			text: 'Results over Time'
		},
		loading: {
			labelStyle: {
				fontSize: 'large'
			},
			style: {
				backgroundColor: '#32324C'
			}
		}
	});
}
